const express = require("express")
const bodyParser = require('body-parser')
const fs = require("fs");
const path = require("path");
config = JSON.parse(fs.readFileSync(path.join(__dirname, '../config.json')));
let app = express();
let post = require("./models/post")
const db = require("./db/db");
const log4js = require('log4js');

log4js.configure({
  appenders: {
    normal: {
      type: 'file', //文件输出
      filename: 'logs/access.log',
      maxLogSize: 1024,
      backups: 3,
      category: 'normal'
    }
  },
  categories: { default: { appenders: ['normal'], level: 'info' } }
});


var logger = log4js.getLogger('normal');

var urlencodedParser = bodyParser.urlencoded({ extended: false })
var jsonParser = bodyParser.json();

app.post('/process_post', function (req, res) {
  // Prepare output in JSON format
  response = {
    first_name: req.body.first_name,
    last_name: req.body.last_name
  };
  first_name = req.body.first_name;
  last_name = req.body.last_name;

  db.run("INSERT INTO users Values($first_name, $last_name)", {
    $first_name: first_name,
    $last_name: last_name
  });
})

app.use(express.static(path.join(__dirname, "../www")));

app.get('/clients/:clientId', function (req, res) {
  db.getClient(req.params.clientId).then(function (rows) {
    res.json(rows)
  })
});

app.post('/serialnumbers', urlencodedParser, function (req, res) {
  if (!req.body) return res.sendStatus(400)
  db.createSerialNumber(req.body.prefix).then(function (serialnumber) {
    res.json(serialnumber)
  })
})

app.post('/proudcts', jsonParser, function (req, res) {
  if (!req.body) return res.sendStatus(400)
  db.createProductInfo(req.body).then(function (productInfo) {
    res.json(productInfo)
  })
})

app.get('/productclasses', function (req, res) {
  db.getProductClasses().then(function (productClass) {
    res.json(productClass)
  })
})

app.post('/productclasses', jsonParser, function (req, res) {
  if (!req.body) return res.sendStatus(400)
  db.createProductClass(req.body)
    .then(function (productClass) {
      res.status(201).json(productClass);
    })
    .catch(function (e) {
      res.status(409).send("UNIQUE constraint failed: product_class.text");
    })
})

app.put('/productclasses/:classId', jsonParser, function (req, res) {
  if (!req.body) return res.sendStatus(400)
  db.updateProductClass(req.params.classId, req.body)
    .then(function (productClass) {
      res.json("success");
    })
    .catch(function (e) {
      res.sendStatus(400);
    })
})


app.get("/units", function (req, res) {
  db.getUnits()
    .then(function (units) {
      res.json(units);
    })
})

app.post("/units", jsonParser, function (req, res) {
  if (!req.body) return res.sendStatus(400)
  db.createUnit(req.body)
    .then(function (productClass) {
      res.status(201).json(productClass);
    })
    .catch(function (e) {
      res.status(409).send("UNIQUE constraint failed: product_class.text");
    })
})

app.delete('/units/:unitId', function (req, res) {
  db.deleteUnit(JSON.parse(req.params.unitId)).then(function () {
    res.json("success");
  })
});

const server = app.listen(config.server.port, function () {
  logger.info(`Server is running on port ${server.address().port}`);
})


process.on('SIGTERM', () => {
  logger.log('Stopping express');
  db.close();
  server.close(() => {
    process.exit(0);
  });
});

